import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  type ActionType,
  PageContainer,
  type ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import {
  Avatar,
  Button,
  Checkbox,
  Form,
  Input,
  Modal,
  message,
  Select,
  Space,
  Tag,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import {
  assignUserRoles,
  createUser,
  deleteUser,
  getRoles,
  getUsers,
  updateUser,
} from '@/services/ant-design-pro/rbac';

const Users: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [roles, setRoles] = useState<API.Role[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<API.UserWithRoles | null>(
    null,
  );
  const [selectedUser, setSelectedUser] = useState<API.UserWithRoles | null>(
    null,
  );
  const [form] = Form.useForm();
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);

  useEffect(() => {
    loadRoles();
  }, []);

  const loadRoles = async () => {
    try {
      const response = await getRoles();
      setRoles(response.data?.filter((role) => role.status === 'active') || []);
    } catch (_error) {
      message.error('加载角色列表失败');
    }
  };

  const handleCreate = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: API.UserWithRoles) => {
    setEditingUser(record);
    form.setFieldsValue({
      name: record.name,
      email: record.email,
      username: record.userid,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      onOk: async () => {
        try {
          await deleteUser(id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (_error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingUser?.userid) {
        await updateUser({
          id: editingUser.userid,
          ...values,
        });
        message.success('更新成功');
      } else {
        await createUser(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (_error) {
      message.error('操作失败');
    }
  };

  const handleRoleAssign = async (record: API.UserWithRoles) => {
    setSelectedUser(record);
    setSelectedRoles(record.roles?.map((r) => r.id || '') || []);
    setRoleModalVisible(true);
  };

  const handleRoleSubmit = async () => {
    if (!selectedUser?.userid) return;

    try {
      await assignUserRoles(selectedUser.userid, selectedRoles);
      message.success('角色分配成功');
      setRoleModalVisible(false);
      actionRef.current?.reload();
    } catch (_error) {
      message.error('角色分配失败');
    }
  };

  const renderAvatar = (avatar: string) => (
    <Avatar src={avatar} icon={<UserOutlined />} />
  );

  const renderName = (name: string) => <strong>{name}</strong>;

  const renderRoles = (userRoles: API.Role[]) => (
    <Space wrap>
      {userRoles?.map((role) => (
        <Tag key={role.id} color="blue">
          {role.name}
        </Tag>
      )) || <Tag color="default">无角色</Tag>}
    </Space>
  );

  const renderPermissionCount = (permissions?: API.Permission[]) =>
    permissions?.length || 0;

  const renderAccess = (access: string) => (
    <Tag color={access === 'admin' ? 'red' : 'green'}>
      {access === 'admin' ? '管理员' : '普通用户'}
    </Tag>
  );

  const columns: ProColumns<API.UserWithRoles>[] = [
    {
      title: '头像',
      dataIndex: 'avatar',
      width: 80,
      render: renderAvatar,
    },
    {
      title: '用户名',
      dataIndex: 'userid',
      key: 'userid',
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: renderName,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      width: 200,
      render: renderRoles,
    },
    {
      title: '部门',
      dataIndex: 'group',
      key: 'group',
      width: 120,
    },
    {
      title: '职位',
      dataIndex: 'title',
      key: 'title',
      width: 120,
    },
    {
      title: '权限数量',
      dataIndex: 'permissions',
      key: 'permissions',
      width: 120,
      render: renderPermissionCount,
    },
    {
      title: '状态',
      dataIndex: 'access',
      key: 'access',
      width: 100,
      render: renderAccess,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Button
          key="role"
          type="link"
          size="small"
          icon={<TeamOutlined />}
          onClick={() => handleRoleAssign(record)}
        >
          角色
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.userid || '')}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户管理',
        breadcrumb: {
          items: [
            {
              title: '系统管理',
            },
            {
              title: '用户管理',
            },
          ],
        },
      }}
    >
      <ProTable<API.UserWithRoles>
        columns={columns}
        actionRef={actionRef}
        rowKey="userid"
        search={{
          labelWidth: 120,
        }}
        request={async (params: any) => {
          const response = await getUsers({
            current: params.current,
            pageSize: params.pageSize,
            name: params.name,
          });
          return {
            data: response.data || [],
            success: response.success,
            total: response.total,
          };
        }}
        columnsState={{
          persistenceKey: 'users-table',
          persistenceType: 'localStorage',
        }}
        rowSelection={{}}
        tableAlertRender={false}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={handleCreate}
            icon={<PlusOutlined />}
          >
            新建用户
          </Button>,
        ]}
      />

      {/* 创建/编辑用户弹窗 */}
      <Modal
        title={editingUser ? '编辑用户' : '新建用户'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
        </Form>
      </Modal>

      {/* 角色分配弹窗 */}
      <Modal
        title={`分配用户角色 - ${selectedUser?.name}`}
        open={roleModalVisible}
        onCancel={() => setRoleModalVisible(false)}
        onOk={handleRoleSubmit}
        width={500}
      >
        <div style={{ marginBottom: 16 }}>
          <p>请为用户 "{selectedUser?.name}" 分配角色：</p>
        </div>
        <Checkbox.Group
          style={{ width: '100%' }}
          value={selectedRoles}
          onChange={setSelectedRoles}
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {roles.map((role) => (
              <Checkbox key={role.id} value={role.id}>
                <div>
                  <strong>{role.name}</strong>
                  <div style={{ color: '#666', fontSize: '12px' }}>
                    {role.description || role.code}
                  </div>
                </div>
              </Checkbox>
            ))}
          </Space>
        </Checkbox.Group>
      </Modal>
    </PageContainer>
  );
};

export default Users;
